package com.luomo.wenyuan.modules.wenyuan.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luomo.wenyuan.common.utils.PageUtils;
import com.luomo.wenyuan.common.utils.Query;
import com.luomo.wenyuan.modules.wenyuan.dao.TReaderDao;
import com.luomo.wenyuan.modules.wenyuan.entity.TReaderEntity;
import com.luomo.wenyuan.modules.wenyuan.service.TReaderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.Map;


@Service("tReaderService")
public class TReaderServiceImpl extends ServiceImpl<TReaderDao, TReaderEntity> implements TReaderService {

    @Autowired
    private TReaderDao tReaderDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String name = (String) params.get("name");
        String id = (String) params.get("id");
        IPage<TReaderEntity> page = this.page(
                new Query<TReaderEntity>().getPage(params),
                new QueryWrapper<TReaderEntity>()
                        .like(StrUtil.isNotBlank(name), "name", name)
                        .like(StrUtil.isNotBlank(id), "id", id)
        );
        return new PageUtils(page);
    }

    @Override
    public String getNextId() {
        String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
        String lastId = tReaderDao.getLastId();
        String id = "";
        if (StrUtil.isBlank(lastId)) {
            //空表
            id = dateStr + "0001";
        } else {
            String lastDate = lastId.substring(0, 8);
            if (!lastDate.equals(dateStr)) {
                //当天第一个
                id = dateStr + "0001";
            } else {
                String no = lastId.substring(8);
                DecimalFormat decimalFormat = new DecimalFormat("0000");
                int i = Integer.parseInt(no) + 1;
                id = dateStr + decimalFormat.format(i);
            }
        }
        return id;
    }

    @Override
    public boolean save(TReaderEntity entity) {
        tReaderDao.save(entity);
        return true;
    }

}